import axios from 'axios'
/**
 * baseURL使用场景
 * 1、代理 代理的是单个地址  不需要用
 * 2、代理 /api  baseURL:'/api'
 * 3、cros baseURL:http://xxx.x.x
 * 
 * headers使用场景
 * 1、数据请求头类型   
 *      content-type: application/x-www-from-urlencoded   数据是字符串样子是  a=1&b=2
 *      Content-Type: application/json   数据类型是json  {a:1,b:2}
 *      Content-Type: form-data  上传文件
 *      hearders:{
 *          Content-Type:'application/json'
 *      }
 * 2、设置token
 */
//统一设置
// let http=axios.create({
//   baseURL: 'http://172.16.124.48:3000',
// //     // timeout: 1000,  //请求超时时间
// //     // headers: {'X-Custom-Header': 'foobar'}
// });
//分开设置
axios.defaults.baseURL = 'http://192.168.2.40:8787';
// axios.defaults.baseURL = 'http://192.168.1.44:8787';
// if(sessionStorage.getItem('token')){
//     axios.defaults.headers['token']=sessionStorage.getItem('token');
// }

axios.interceptors.request.use(function (config) { //当所有axios发送请求的时候进行拦截
  //获取token
  let token = sessionStorage.getItem('token');
  //有没有token,有的话就加在request里面
  token && (config.headers['token'] = token);
  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (request) {//所有axios的响应进行拦截
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  let token = sessionStorage.getItem('token');
  token && (request.headers['token'] = token);
  return request;
}, function (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  if (error.request.status == 401) { //token失效了
    sessionStorage.removeItem('token');
    alert('请先进行登录!!!!')
    window.location.href = '/';
  }
  return Promise.reject(error);
});


export default axios;